package com.taxinfo.controller;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.taxinfo.common.ClientSession;
import com.taxinfo.component.alert.MyAlert;
import com.taxinfo.pojo.dto.DecDocumentRecDto;
import com.taxinfo.pojo.dto.LoginDto;
import com.taxinfo.pojo.dto.StandardSubDto;
import com.taxinfo.pojo.dto.DecDocumentRecDto;
import com.taxinfo.service.DecDocumentRecService;
import com.taxinfo.service.StandardSubService;
import com.taxinfo.utils.SpringUtil;
import com.taxinfo.view.declaration.DecDocumentTable;
import com.taxinfo.view.standard.StandardSubTable;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.stage.FileChooser;
import javafx.util.Duration;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

/**
 * 税务申报文档管理
 */
public class DecDocumentRecController implements Initializable {
    @FXML
    public TextField decYear;
    @FXML
    public RadioButton year;
    @FXML
    public RadioButton quarter;
    @FXML
    public RadioButton month;
    @FXML
    public ToggleGroup group;
    @FXML
    public ScrollPane scrollPane;

    private DecDocumentTable table;

    private final DecDocumentRecService decDocumentRecService  = (DecDocumentRecService) SpringUtil.getBean("DecDocumentRecServiceImpl");

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        List<DecDocumentRecDto> dtoList = decDocumentRecService.selectAllData();
        table = new DecDocumentTable(dtoList);
        scrollPane.setContent(table);
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int year = cal.get(Calendar.YEAR);
        decYear.setText(String.valueOf(year));
        ContextMenu cxmenu = new ContextMenu();
        MenuItem robotWrite = new MenuItem("机器人智能填报");
        MenuItem downloadXls = new MenuItem("编辑申报文件");

        robotWrite.setOnAction(event -> {
            String isSb = table.getSelectedData().getIsSb();
            if("已申报".equals(isSb)){
                new MyAlert(Alert.AlertType.ERROR, "该申报单已申报！").show();
                return;
            }
            LoginDto loginDto =(LoginDto) ClientSession.getAttribute("user");
            String returnVal = decDocumentRecService.callRobot(table,loginDto);
            if (StringUtils.isNotBlank(returnVal)){
                JSONObject jsonObj = new JSONObject(returnVal);
                if ("0".equals(jsonObj.get("code"))){
                    new MyAlert(Alert.AlertType.INFORMATION, "机器人智能填报调用完成！").show();
                }else{
                    new MyAlert(Alert.AlertType.ERROR, "机器人智能填报调用失败！").show();
                }
            }else{
                new MyAlert(Alert.AlertType.ERROR, "机器人智能填报失败！").show();
            }
            // 创建一个 KeyFrame，每隔 1 秒执行一次
            KeyFrame keyFrame = new KeyFrame(Duration.seconds(30), event10 -> {
                // 执行轮询操作
                findInfo();
            });
            // 创建 Timeline，并设置循环次数为无限
            Timeline timeline = new Timeline(keyFrame);
            timeline.setCycleCount(Timeline.INDEFINITE);
            timeline.play(); // 启动定时器

        });
        downloadXls.setOnAction(event -> {
            String filePath = table.getSelectedData().getDecFileAddr();
            if (Desktop.isDesktopSupported()) {
                Desktop desktop = Desktop.getDesktop();
                try {
                    desktop.open(new File(filePath));
                } catch (IOException ex) {
                    new MyAlert(Alert.AlertType.WARNING, "无法打开文件！".concat(filePath)).show();
                }
            } else {
                new MyAlert(Alert.AlertType.WARNING, "桌面操作不被支持！").show();
            }
        });

        // 将菜单项添加到ContextMenu中
        cxmenu.getItems().addAll(robotWrite,downloadXls);
        scrollPane.setContextMenu(cxmenu);
    }

    @FXML
    private void findInfo() {
        String pDecYear = decYear.getText().trim();
        //1:年度,2:季度,3:月度',
        String pSubType = "";
        if(quarter.isSelected()){
            pSubType = "季度";
        }else if(year.isSelected()){
            pSubType = "年度";
        }else if(month.isSelected()){
            pSubType = "月度";
        }

        List<DecDocumentRecDto> dtoList = decDocumentRecService.selectDataByCondition(decYear.getText().trim(),pSubType);
        table.clearData();
        if (dtoList != null && dtoList.size()>0) {

            for (DecDocumentRecDto bean : dtoList){
                table.addBean(bean);
            }

        } else {
            new MyAlert(Alert.AlertType.INFORMATION, "没有找到您查找的申报文件记录信息！").show();
        }
    }
}
